package com.mingke.chat.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;

/**
 * @author mingke
 * @function TODO
 * @date 2021/12/14
 */
public class AcceptHandler implements CompletionHandler<AsynchronousSocketChannel, AsynchronousServerSocketChannel> {
    //日志框架
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public void completed(AsynchronousSocketChannel socketChannel, AsynchronousServerSocketChannel attachment) {
        try {
            log.info("IP地址为："+socketChannel.getRemoteAddress().toString()+"的客户端连接成功");
        }catch (Exception e) {
            e.printStackTrace();
        }

        if(socketChannel.isOpen()) {
            try {
                //设置服务通道的参数
                socketChannel.setOption(StandardSocketOptions.TCP_NODELAY, true);
                socketChannel.setOption(StandardSocketOptions.SO_SNDBUF, 10240);
                socketChannel.setOption(StandardSocketOptions.SO_RCVBUF, 10240);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //设置读数据的回调
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            byteBuffer.clear();
            socketChannel.read(byteBuffer, byteBuffer, new ReadHandler(socketChannel));
        }

        //设置服务通道继续监听客户端连接请求
        attachment.accept(attachment, this);
    }

    @Override
    public void failed(Throwable exc, AsynchronousServerSocketChannel attachment) {
        log.error("客户端连接失败");
        exc.printStackTrace();
    }
}
